import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
// import {Indicator, Toast} from 'mint-ui'
import {ToastPlugin, LoadingPlugin} from 'vux'

Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)

const addTimestampToUrl = config => {
    // url添加参数
    let url = config.url, params = config.params, method = config.method
    url = '/_api' + url // 使用'/_api'识别接口请求
    // if (process.env.NODE_ENV !== 'production' && url.indexOf('http') < 0) url = '/_api' + url // 开发环境使用'/_api'识别代理
    if (method === 'get' && params && Object.keys(params).length > 0) {
        // get请求统一将params序列化
        url = appendParams(url, qs.stringify(params))
        config.params = {}
    }
    // url请求加上时间戳
    config.url = encodeURI(appendParams(url, '_t=' + new Date().getTime()))

    function appendParams(url, params) {
        if (url.indexOf('?') >= 0) {
            return url + '&' + params
        } else {
            return url + '?' + params
        }
    }

    Vue.$vux.loading.show()
    return config
}, get = (url, params) => {
    return axios.get(url, {
        params
    })
}, post = (url, data) => {
    return axios.post(url, data)
}

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    return addTimestampToUrl(config)
}, function (error) {
    return Promise.reject(error)
})

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    Vue.$vux.loading.hide()
    if (response.headers.redirect) {
        let redirect = response.headers.redirect, url
        redirect = redirect.split('targetUrl=')
        url = redirect[0] + 'targetUrl=' + encodeURI(location.href.replace(location.search, ''))
        window.location.href = url
    } else {
        if (response.config.url.indexOf('allResponse') > -1) {
            return response
        } else {
            if (!response.data.success && response.data.message) {
                Vue.$vux.toast.text(response.data.message, 'middle')
            }
            return response.data
        }
    }
}, function (error) {
    Vue.$vux.loading.hide()
    // 错误拦截
    if (error.response.data.message) {
        Vue.$vux.toast.text(error.response.data.message, 'middle')
    }
    return Promise.reject(error)
})

export default {
    get,
    post
}
